//
//  YMPhotoChooseManager.m
//  SmartCar
//
//  Created by y s on 2022/12/7.
//

#import "YMPhotoChooseManager.h"
#import <MobileCoreServices/MobileCoreServices.h>
#import "YMDeviceTools.h"
#import "YMAliYunUtil.h"


@interface YMPhotoChooseManager ()<UIImagePickerControllerDelegate, UINavigationControllerDelegate>

@property (nonatomic, strong) UIViewController *vcCurrent;

@property (nonatomic, assign) BOOL canVideo;

@end


@implementation YMPhotoChooseManager


- (instancetype)init{
    self = [super init];
    if (self) {

    }
    return self;
}


- (void)choosePhotoAction:(NSString *)title
                 canVideo:(BOOL)canVideo
                       vc:(UIViewController *)vc
{
    self.vcCurrent = vc;
    self.canVideo = canVideo;
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:title
                                                                 message:nil
                                                          preferredStyle:UIAlertControllerStyleActionSheet];
    __weak typeof(self) weakSelf = self;
    UIAlertAction *cameraAction = [UIAlertAction actionWithTitle:@"拍照"
                                                         style:UIAlertActionStyleDefault
                                                       handler:^(UIAlertAction *action) {
                                                           [weakSelf changeCamera];
                                                       }];
    UIAlertAction *photoAction = [UIAlertAction actionWithTitle:@"从相册选择"
                                                        style:UIAlertActionStyleDefault
                                                      handler:^(UIAlertAction *action) {
                                                          [weakSelf changePhoto];
                                                      }];
    UIAlertAction *cancelAction=[UIAlertAction actionWithTitle:KLanguage(@"cancle_txt")
                                                         style:UIAlertActionStyleCancel
                                                       handler:nil];
    [alert addAction:cameraAction];
    [alert addAction:photoAction];
    if (canVideo){
        UIAlertAction *videoAction = [UIAlertAction actionWithTitle:@"从视频库选择"
                                                            style:UIAlertActionStyleDefault
                                                          handler:^(UIAlertAction *action) {
                                                              [weakSelf chooseVideo];
                                                          }];
        [alert addAction:videoAction];
    }
    [alert addAction:cancelAction];
    [vc presentViewController:alert animated:YES completion:nil];
}

- (void)chooseVideoAction:(NSString *)title
                       vc:(UIViewController *)vc{
    WEAK_SELF;
    self.vcCurrent = vc;
    self.canVideo = YES;
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:title
                                                                 message:nil
                                                          preferredStyle:UIAlertControllerStyleActionSheet];
    UIAlertAction *videoAction = [UIAlertAction actionWithTitle:@"从视频库选择"
                                                        style:UIAlertActionStyleDefault
                                                      handler:^(UIAlertAction *action) {
                                                          [weakSelf chooseVideo];
                                                      }];
    UIAlertAction *cancelAction=[UIAlertAction actionWithTitle:KLanguage(@"cancle_txt")
                                                         style:UIAlertActionStyleCancel
                                                       handler:nil];
    [alert addAction:videoAction];
    [alert addAction:cancelAction];
    [vc presentViewController:alert animated:YES completion:nil];
}


//照相
- (void)changeCamera
{
#if TARGET_IPHONE_SIMULATOR
#else
    if (![UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) {
            return;
    }
    UIImagePickerController *imagePicker = [[UIImagePickerController alloc] init];
    imagePicker.delegate = self;
    imagePicker.sourceType = UIImagePickerControllerSourceTypeCamera;
    imagePicker.mediaTypes = @[(NSString *)kUTTypeImage];
    [_vcCurrent presentViewController:imagePicker animated:YES completion:nil];
#endif
}

//照片
- (void)changePhoto
{
    if (![UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypePhotoLibrary]) {
           return;
    }
    UIImagePickerController *imagePicker = [[UIImagePickerController alloc] init];
    imagePicker.delegate = self;
    imagePicker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
    imagePicker.mediaTypes = @[(NSString *)kUTTypeImage];
    imagePicker.allowsEditing = NO;
    [_vcCurrent presentViewController:imagePicker animated:YES completion:nil];
}

- (void)chooseVideo{
    if (![UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypePhotoLibrary]) {
           return;
    }
    UIImagePickerController *imagePicker = [[UIImagePickerController alloc] init];
    imagePicker.delegate = self;
    imagePicker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
    imagePicker.mediaTypes = @[(NSString *)kUTTypeMovie];
    imagePicker.allowsEditing = NO;
    [_vcCurrent presentViewController:imagePicker animated:YES completion:nil];
}



#pragma mark - UIImagePickerControllerDelegate
- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker
{
    [_vcCurrent dismissViewControllerAnimated:YES completion:nil];
}

- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info
{
    NSLog(@"++++++++++++%@",info);
    NSString *mediaType = info[UIImagePickerControllerMediaType];
    
    NSData *data;
    NSString *mimeType;
    //名称 时间戳+用户Id
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    dateFormatter.dateFormat = @"yyyyMMddHHmmss";
    NSString *TIMESTAMP = [dateFormatter stringFromDate:[NSDate date]];
    
    int arcNum = arc4random() % 100;
    __block NSString *fileName = [NSString stringWithFormat:@"%@0%@",[YMMyModel shared].userPhone,TIMESTAMP];
    if (arcNum < 10){
        fileName = [fileName stringByAppendingFormat:@"0%d",arcNum];
    }else{
        fileName = [fileName stringByAppendingFormat:@"%d",arcNum];
    }
    __block NSString *type = @"";
    if ([mediaType isEqualToString:(NSString *)kUTTypeImage]){
        UIImage *image = info[UIImagePickerControllerEditedImage];
        if (image == nil){
            image = info[UIImagePickerControllerOriginalImage];
        }
        if (picker.sourceType == UIImagePickerControllerSourceTypeCamera) {
            UIImageWriteToSavedPhotosAlbum(image, self, @selector(image:didFinishSavingWithError:contextInfo:), nil);
        }
        UIImage *newimage;
        if (image.size.width>1800) {
            newimage = [self resizeImage:image Width:image.size.width*0.3 Height:image.size.height*0.3];
        }else if (image.size.width<=1800 && image.size.width>1000) {
            newimage = [self resizeImage:image Width:image.size.width*0.4 Height:image.size.height*0.4];
        }else {
            newimage=image;
        }
        
        if (newimage.size.width > 1800) {
            data= UIImageJPEGRepresentation([self resizeImage:newimage Width:newimage.size.width*0.3 Height:newimage.size.height*0.3],0.8);
        }else {
            data= UIImageJPEGRepresentation(newimage,0.8);
        }
        if ([data length] >= 50*1024) {
            data = UIImageJPEGRepresentation(newimage,0.3);
        }
        mimeType = @"image/jpeg";
        fileName = [fileName stringByAppendingString:@".jpg"];
        type = @"photo";
    }else if (_canVideo && [mediaType isEqualToString:(NSString *)kUTTypeMovie]){
        NSURL *videoUrl = info[UIImagePickerControllerMediaURL];
        data = [NSData dataWithContentsOfURL:videoUrl];
        mimeType = @"video/quicktime";
        fileName = [fileName stringByAppendingString:@".mov"];
        type = @"video";
    }
    
    __weak typeof(self) weakSelf = self;
    [_vcCurrent dismissViewControllerAnimated:YES completion:nil];
    [SHUD showWait:_vcCurrent.view];
    [[YMAliYunUtil shared] aliyunUploadFile:data fileName:fileName success:^(NSString * _Nonnull strUrl) {
        dispatch_async(dispatch_get_main_queue(), ^{
            [SHUD hide:weakSelf.vcCurrent.view];
        });
        if (weakSelf.uploadSucessBlock){
            weakSelf.uploadSucessBlock(strUrl);
        }
    } failure:^{
        dispatch_async(dispatch_get_main_queue(), ^{
            [SHUD hide:weakSelf.vcCurrent.view];
            [SHUD showInfo:@"上传失败"];
        });
        if (weakSelf.uploadErrorBlock){
            weakSelf.uploadErrorBlock(@"上传失败");
        }
    }];
}

- (void)image:(UIImage *)image didFinishSavingWithError:(NSError*)error contextInfo:(void*)contextInfo
{
    if (error != NULL) {
        
    } else {
        
    }
}
- (UIImage *)resizeImage:(UIImage *)orgImg Width:(NSInteger)tarWidth Height:(NSInteger)tarHeight
{
    UIImage *retImage;
    if (orgImg.size.width > tarWidth || orgImg.size.height > tarHeight)
    {
        CGFloat w = orgImg.size.width;
        CGFloat h = orgImg.size.height;
        float k = (float) tarWidth / w;
        if ((float) w / tarWidth > (float) h / tarHeight) {
            w = tarWidth;
            h = (int)(h * k);
        } else {
            k = (float) tarHeight / h;
            h = tarHeight;
            w = (int) (w * k);
        }
        CGSize imgSize = CGSizeMake(w, h);
        UIGraphicsBeginImageContext(imgSize);
        CGRect imgRect = CGRectMake(0.0, 0.0, imgSize.width, imgSize.height);
        [orgImg drawInRect:imgRect];
        retImage = UIGraphicsGetImageFromCurrentImageContext();
        UIGraphicsEndImageContext();
    } else {
        retImage = orgImg;
    }
    return retImage;
}



@end
